<?php

declare(strict_types=1);

namespace App\Model;


use App\Dao\CityIpDao;
use App\Utils\MemcacheClient;

/**
 * @property int $id
 * @property int $type 0 省份 1 城市 2 ip列表
 * @property string $content
 * @property int $status 0 关闭 1 开启
 * @property int $sub_type 子类型 0 托管 1 脚本 2 充值 3 首页列表 4进入审核环境
 */
class Forbidden extends Model
{
    /**
     * The table associated with the model.
     */
    protected ?string $table = 'tb_forbidden';

    /**
     * The attributes that are mass assignable.
     */
    protected array $fillable = [];

    /**
     * The attributes that should be cast to native types.
     */
    protected array $casts = ['id' => 'integer', 'type' => 'integer', 'status' => 'integer', 'sub_type' => 'integer'];


    /**
     * IP所在地区是否在屏蔽地区
     * @param $ip
     * @return bool
     */
    public static function forbiddenCity($ip)
    {
        $ipcache = CityIpDao::getInstance()->getProvinceCity($ip);
        $province = $ipcache["province"] ?: "";
        $city = $ipcache['city'] ?: '';
        if (!empty($province) || !empty($city)) {
            $cityArr = self::query()->where('status', 1)->where('sub_type', 4)->pluck("content")->toArray();
            if (in_array($province, $cityArr) || in_array($city, $cityArr)) {
                return true;
            }
        }
        return false;

    }

    public function getData($type = 0, $sub_type = 0)
    {
        $type = intval($type);
        $sub_type = intval($sub_type);
        $data = MemcacheClient::getInstance()->get('forbidden_type_' . $type . '_' . $sub_type);
        if (empty($data)) {
            // $sql = "select * from {$this->table} where type = ? and sub_type = ?";
            // $pd = $this->createCommand($sql);
            // $pd->execute(array($type, $sub_type));
            // $rs = $pd->fetchAll(PDO::FETCH_ASSOC);
            // $data = [];
            // foreach ($rs as $v) {
            //     $data[] = $v['content'];
            // }
            $data = self::query()->where('type', $type)->where('sub_type', $sub_type)->pluck("content")->toArray();
            MemcacheClient::getInstance()->set('forbidden_type_' . $type . '_' . $sub_type, $data, 600);

        }
        return $data;
    }

    /*
     *  sub_type 类型 0 托管、push消息 1 脚本 2 充值 3 首页列表
     * */
    public function check($city = '', $province = '', $sub_type = 0)
    {
        if (!empty($city)) {
            $data = $this->getData(1, $sub_type);
            if (!empty($data) && in_array($city, $data)) {
                return false;
            }
        }
        if (!empty($province)) {
            $data = $this->getData(0, $sub_type);
            if (!empty($data) && in_array($province, $data)) {
                return false;
            }
        }
        return true;
    }


}
